/**
 * @file platform_config.c
 * @brief 平台配置加载器实现
 * @details 从配置文件加载平台对接相关配置
 * 
 * @author zyb
 * @date 2025-11-04
 * @version 1.0
 */

#include "../include/platform_config.h"
#include "../../../common/logs/include/logger.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

#define LOG_MODULE_NAME "PLATFORM_CONFIG"

/* 默认值 */
#define DEFAULT_MQTT_PORT 21883
#define DEFAULT_MQTT_KEEPALIVE 60
#define DEFAULT_MQTT_QOS 1
#define DEFAULT_MQTT_CLEAN_SESSION true
#define DEFAULT_MQTT_USE_TLS false
#define DEFAULT_AUTO_REGISTER true
#define DEFAULT_AUTO_GET_MODEL true
#define DEFAULT_MODEL_TYPE "simple_model"

/**
 * @brief 配置项回调函数
 */
static int config_item_callback(const char* key, const char* value, void* user_data) {
    platform_full_config_t* config = (platform_full_config_t*)user_data;
    
    /* MQTT配置 */
    if (strcmp(key, "mqtt_broker") == 0) {
        strncpy(config->mqtt.broker, value, sizeof(config->mqtt.broker) - 1);
    } else if (strcmp(key, "mqtt_port") == 0) {
        config->mqtt.port = (uint16_t)atoi(value);
    } else if (strcmp(key, "mqtt_client_id") == 0) {
        strncpy(config->mqtt.client_id, value, sizeof(config->mqtt.client_id) - 1);
    } else if (strcmp(key, "mqtt_username") == 0) {
        strncpy(config->mqtt.username, value, sizeof(config->mqtt.username) - 1);
    } else if (strcmp(key, "mqtt_password") == 0) {
        strncpy(config->mqtt.password, value, sizeof(config->mqtt.password) - 1);
    } else if (strcmp(key, "mqtt_keepalive") == 0) {
        config->mqtt.keepalive = (uint16_t)atoi(value);
    } else if (strcmp(key, "mqtt_qos") == 0) {
        config->mqtt.qos = (mqtt_qos_t)atoi(value);
    } else if (strcmp(key, "mqtt_clean_session") == 0) {
        config->mqtt.clean_session = (strcmp(value, "y") == 0 || strcmp(value, "yes") == 0);
    } else if (strcmp(key, "mqtt_use_tls") == 0) {
        config->mqtt.use_tls = (strcmp(value, "y") == 0 || strcmp(value, "yes") == 0);
    }
    /* 设备信息 */
    else if (strcmp(key, "product_key") == 0) {
        strncpy(config->device.product_key, value, sizeof(config->device.product_key) - 1);
    } else if (strcmp(key, "device_name") == 0) {
        strncpy(config->device.device_name, value, sizeof(config->device.device_name) - 1);
    } else if (strcmp(key, "device_secret") == 0) {
        strncpy(config->device.device_secret, value, sizeof(config->device.device_secret) - 1);
    } else if (strcmp(key, "product_secret") == 0) {
        strncpy(config->device.product_secret, value, sizeof(config->device.product_secret) - 1);
    }
    /* 平台配置 */
    else if (strcmp(key, "auto_register") == 0) {
        config->auto_register = (strcmp(value, "y") == 0 || strcmp(value, "yes") == 0);
    } else if (strcmp(key, "auto_get_model") == 0) {
        config->auto_get_model = (strcmp(value, "y") == 0 || strcmp(value, "yes") == 0);
    } else if (strcmp(key, "model_type") == 0) {
        strncpy(config->model_type, value, sizeof(config->model_type) - 1);
    }
    
    return 0;
}

/**
 * @brief 加载平台配置
 */
int platform_config_load(platform_full_config_t* config, const char* config_file) {
    if (config == NULL || config_file == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "配置参数为空");
        return -1;
    }
    
    LOG_INFO(LOG_MODULE_NAME, "加载平台配置文件: %s", config_file);
    
    /* 初始化配置结构 */
    memset(config, 0, sizeof(platform_full_config_t));
    
    /* 设置默认值 */
    config->mqtt.port = DEFAULT_MQTT_PORT;
    config->mqtt.keepalive = DEFAULT_MQTT_KEEPALIVE;
    config->mqtt.qos = DEFAULT_MQTT_QOS;
    config->mqtt.clean_session = DEFAULT_MQTT_CLEAN_SESSION;
    config->mqtt.use_tls = DEFAULT_MQTT_USE_TLS;
    config->auto_register = DEFAULT_AUTO_REGISTER;
    config->auto_get_model = DEFAULT_AUTO_GET_MODEL;
    strncpy(config->model_type, DEFAULT_MODEL_TYPE, sizeof(config->model_type) - 1);
    
    /* 打开配置文件 */
    FILE* fp = fopen(config_file, "r");
    if (fp == NULL) {
        LOG_ERROR(LOG_MODULE_NAME, "无法打开配置文件: %s", config_file);
        return -1;
    }
    
    char line[1024];
    int line_num = 0;
    
    while (fgets(line, sizeof(line), fp)) {
        line_num++;
        
        /* 去除换行符 */
        line[strcspn(line, "\r\n")] = '\0';
        
        /* 跳过空行和注释行 */
        if (strlen(line) == 0 || line[0] == '#') {
            continue;
        }
        
        /* 解析key=value格式 */
        char* eq = strchr(line, '=');
        if (eq == NULL) {
            LOG_WARN(LOG_MODULE_NAME, "第%d行格式错误，跳过: %s", line_num, line);
            continue;
        }
        
        *eq = '\0';
        char* key = line;
        char* value = eq + 1;
        
        /* 去除首尾空格 */
        while (*key == ' ' || *key == '\t') key++;
        while (value[strlen(value) - 1] == ' ' || value[strlen(value) - 1] == '\t') {
            value[strlen(value) - 1] = '\0';
        }
        
        /* 处理配置项 */
        config_item_callback(key, value, config);
    }
    
    fclose(fp);
    
    LOG_DEBUG(LOG_MODULE_NAME, "平台配置文件加载成功");
    
    return 0;
}

/**
 * @brief 打印平台配置
 */
void platform_config_print(const platform_full_config_t* config) {
    if (config == NULL) {
        return;
    }
    
    LOG_DEBUG(LOG_MODULE_NAME, "==================== 平台配置 ====================");
    LOG_DEBUG(LOG_MODULE_NAME, "MQTT配置:");
    LOG_DEBUG(LOG_MODULE_NAME, "  Broker: %s", config->mqtt.broker);
    LOG_DEBUG(LOG_MODULE_NAME, "  Port: %u", config->mqtt.port);
    if (strlen(config->mqtt.client_id) > 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "  ClientID: %s", config->mqtt.client_id);
    }
    if (strlen(config->mqtt.username) > 0) {
        LOG_DEBUG(LOG_MODULE_NAME, "  Username: %s", config->mqtt.username);
    }
    LOG_DEBUG(LOG_MODULE_NAME, "  KeepAlive: %u", config->mqtt.keepalive);
    LOG_DEBUG(LOG_MODULE_NAME, "  QoS: %d", config->mqtt.qos);
    LOG_DEBUG(LOG_MODULE_NAME, "  CleanSession: %s", config->mqtt.clean_session ? "是" : "否");
    LOG_DEBUG(LOG_MODULE_NAME, "  UseTLS: %s", config->mqtt.use_tls ? "是" : "否");
    LOG_DEBUG(LOG_MODULE_NAME, "设备信息:");
    LOG_DEBUG(LOG_MODULE_NAME, "  ProductKey: %s", config->device.product_key);
    LOG_DEBUG(LOG_MODULE_NAME, "  DeviceName: %s", config->device.device_name);
    LOG_DEBUG(LOG_MODULE_NAME, "  DeviceSecret: %s", config->device.device_secret[0] ? "***" : "(未设置)");
    LOG_DEBUG(LOG_MODULE_NAME, "  ProductSecret: %s", config->device.product_secret[0] ? "***" : "(未设置)");
    LOG_DEBUG(LOG_MODULE_NAME, "平台配置:");
    LOG_DEBUG(LOG_MODULE_NAME, "  AutoRegister: %s", config->auto_register ? "是" : "否");
    LOG_DEBUG(LOG_MODULE_NAME, "  AutoGetModel: %s", config->auto_get_model ? "是" : "否");
    LOG_DEBUG(LOG_MODULE_NAME, "  ModelType: %s", config->model_type);
    LOG_DEBUG(LOG_MODULE_NAME, "===================================================");
}
